package utils

import (
	"time"
	config "todolist-go/src/Config"

	"github.com/dgrijalva/jwt-go"
)

//生成Jwt
func CreateToken(userId int64) (string, error) {
	builder := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
		"uid": userId,
		"exp": time.Now().Add(time.Minute * 15).Unix(),
	})
	token, err := builder.SignedString([]byte(config.JwtSecret))
	if err != nil {
		return "", err
	}
	return token, nil
}

//解析Token
func ParseToken(token string) (int64, error) {
	claim, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.JwtSecret), nil
	})
	if err != nil {
		return 0, err
	}
	//控制台报错得到的是float64类型，需要强转
	return int64(claim.Claims.(jwt.MapClaims)["uid"].(float64)), nil
}
